package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	_ "net/http/pprof"

	"file-download-server/controller"
	"file-download-server/service"

	"github.com/prometheus/client_golang/prometheus/promhttp"
)

func main() {
	fileService := service.NewFileService()
	fileController := controller.NewFileController(fileService)

	mux := http.NewServeMux()
	mux.HandleFunc("/api/file/upload", fileController.UploadHandler)
	mux.HandleFunc("/api/file/download", fileController.DownloadHandler)
	mux.HandleFunc("/api/file/list", fileController.ListTasksHandler)
	mux.HandleFunc("/api/file/deleteFile", fileController.DeleteFileHandler)
	mux.HandleFunc("/api/file/deleteTask", fileController.DeleteTaskHandler)
	mux.HandleFunc("/api/file/get", fileController.GetTaskHandler)
	mux.HandleFunc("/api/file/listFiles", fileController.ListFilesHandler)
	mux.HandleFunc("/api/file/updateFile", fileController.UpdateFileHandler)
	mux.HandleFunc("/api/file/downloadFromURL", fileController.DownloadFromURLHandler)

	// Prometheus metrics
	mux.Handle("/metrics", promhttp.Handler())

	// 启动 pprof（独立端口）
	go func() {
		log.Println("[pprof] 监听端口 :6060")
		log.Fatal(http.ListenAndServe(":6060", nil))
	}()

	srv := &http.Server{
		Addr:    ":8080",
		Handler: mux,
	}

	go func() {
		log.Println("文件下载服务启动成功，端口:8080")
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("服务器启动失败: %v", err)
		}
	}()

	// 优雅关闭
	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
	<-stop

	log.Println("接收到中断信号，正在关闭...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("服务器关闭失败: %v", err)
	}
	log.Println("服务已安全关闭")
}
